package spe.xml;

import java.beans.PropertyChangeEvent;
import java.util.Iterator;
import java.util.Map;

import spe.model.spem.ProcessPackage;
import spe.model.spem.SPEMElement;

public class ProcessPackageAdapter extends SPEXmlAdapter
{

	public ProcessPackageAdapter()
	{
	}
	
	@Override
	protected void initialize()
	{
		super.initialize();
		String key;
		ProcessPackage pp = (ProcessPackage) semanticElement;
		if(pp != null)
		{
			Map<String, Object> attr = pp.getAttributes();
			Iterator<String> iter = attr.keySet().iterator();
			while(iter.hasNext())
			{
				key = iter.next();
				setAttribute(key, attr.get(key).toString());
			} 
		}
	}
	
	@Override
	public void initialize(SPEMElement element)
	{
		super.initialize(element);
		ProcessPackage pp = (ProcessPackage) semanticElement;
		
		Map<String, String> attr = getAttributes();
		Iterator<String> iter = attr.keySet().iterator();
		String key;
		while(iter.hasNext())
		{
			key = iter.next();
			if(key.equals("id"))
				pp.setId(attr.get(key));
			
			if(key.equals("name"))
				pp.setName(attr.get(key));
		}

		pp.addPropertyChangeListener(this);
	}

	@Override
	protected void doModelUpdate(String name, String newValue) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void doModelAdd(SPEXmlAdapter child) 
	{
		SPEMElement childElement = getSemanticElementFor(child);
		ProcessPackage pp = (ProcessPackage) this.getSemanticElement();
		pp.addChildElement(childElement);			
		child.initialize(childElement);
	}
	
	private SPEMElement getSemanticElementFor(SPEXmlAdapter child)
	{
		return child.getSemanticElement()!=null?child.getSemanticElement():createSemanticElementFor(child);
	}


	@Override
	protected void doModelRemove(SPEXmlAdapter child) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void doPropertyChange(PropertyChangeEvent event)
	{
		String propertyName = event.getPropertyName();
		
		if(propertyName.equals("Element"))
		{
			SPEMElement element = (SPEMElement) event.getNewValue();
			addElement(element);
		}
		else if(propertyName.equals("name"))
		{
			setAttribute("name", event.getNewValue().toString());
		}

	}

}
